<?php
/**
 * Created by PhpStorm.
 * User: xiongrui
 * Date: 2017-08-21
 * Time: 22:13
 */

namespace app\admin\controller;


use app\common\controller\Admin;
use app\common\model\Order as OrderModel;
use app\common\model\OrderShoplist;

class PlaceOrder extends Admin
{

    public function index(){
        $map = $this->createMap();
        $count = OrderModel::where($map)->count();
        $list = OrderModel::with('OrderShoplist.Goods')->where($map)->order('id desc')->paginate(10,false,array('query' => $this->request->param()));
        $sum = OrderModel::where($map)->sum('total');

        $orderList =  OrderModel::with('OrderShoplist')->where($map)->select();

        $orderListSum = 0;
        foreach ($orderList as $key => $value) {
          foreach ($value->OrderShoplist as $key_s => $value_s) {
            $orderListSum += $value_s->price* $value_s->num;
            $orderCostPrice += $value_s->cost_price * $value_s->num;
            $orderAgentPrice += $value_s->agent_price * $value_s->num;
          }
        }

        // $rl = model('Goodsrule')->select();
        // foreach ($rl as $k => $v) {
        //   if($v->agent_price > 0){
        //     echo $v->agent_price.'<br />';
        //   //  OrderShoplist::where('rule_id', $v->id)->update(['cost_price'=> $v->cost_price, 'agent_price'=> $v->agent_price]);
        //   }
        // }
        $data = [
            'list' => $list,
            'count' => $count,
            'sum' => $sum,
            'orderListSum' => $orderListSum,
            'orderCostPrice' => $orderCostPrice,
            'orderAgentPrice' => $orderAgentPrice,
            'agent' => $orderListSum-$orderAgentPrice,
        ];
        $this->assign($data);
        $this->setMeta('全部订单');
        return $this->fetch();
    }

    public function createMap(){
        input('out_trade_no') ? $map['out_trade_no'] = array('like', '%'.input('out_trade_no').'%') : '';
        input('wxname') ? $map['nick_name'] = array('like', '%'.input('wxname').'%') : '';
        input('rebate_code') ? $map['rebate_code'] = input('rebate_code') : '';
        input('pay') ? $map['pay'] = input('pay') : '';
        input('buystatus') ? $map['buystatus'] = input('buystatus') : '';
        if(input('start') && input('end')){
            $map['create_time'] = array('between time', [input('start'), input('end')]);
            $map['buystatus'] = array('gt','0');
        }
        $map['index_type'] = 2; //产地直发
        if(getGroupId()==6){
          $map['rebate_code'] = session('user_auth.uid');
        }
        return $map;
    }

    public function addOrderNo($id, $order_no){
        $result = OrderShoplist::where('id', $id)->update(['order_no'=>$order_no]);
        if($result){
            return $this->success('添加成功');
        }
    }

    public function createNewsStraightToExl(){
        vendor('phpoffice.phpexcel.Classes.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->getProperties()->setCreator("鲜果屋")
            ->setLastModifiedBy("鲜果屋")
            ->setTitle("订单数据")
            ->setSubject("订单数据")
            ->setDescription("订单数据")
            ->setKeywords("订单")
            ->setCategory("Test result file");
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '姓名')
            ->setCellValue('B1', '电话')
            ->setCellValue('C1', '快递单号')
            ->setCellValue('D1', '地址')
            ->setCellValue('E1', '购买产品')
            ->setCellValue('F1', '数量')
            ->setCellValue('G1', '下单时间');

        $map = $this->createMap();
        $list = OrderModel::where($map)->order('id desc')->select();

        $i = 2;
        foreach ($list as $key => $value) {

            if($value->OrderShoplist){
                foreach ($value->OrderShoplist as $key_s => $value_s) {
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$i, $value['user_name'])
                        ->setCellValue('B'.$i, $value['tel'])
                        ->setCellValueExplicit('C'.$i, $value_s['order_no'], \PHPExcel_Cell_DataType::TYPE_STRING)
                        ->setCellValue('D'.$i, $value['address'])
                        ->setCellValue('E'.$i,  $value_s['good_name'])
                        ->setCellValue('F'.$i, $value_s['num'])
                        ->setCellValue('G'.$i, $value['create_time']);
                        $i = $i+1;
                }

            }

        }


        $filename = date('y-m-d h:i:s',time());
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }




      public function edit($id) {
    		if (!$id) {
    			return $this->error("非法操作！");
    		}
    		if (IS_POST) {
    			$result = model('Order')->change();
    			return $this->success("编辑成功！", Cookie('__forward__'));
    		} else {
          $info = model('Order')->get($id);
          $shoplist = model('OrderShoplist')->all(['order_id'=>$id]);

    			$this->assign('info',$info);
    			$this->assign('shoplist',$shoplist);
    			$this->setMeta('订单详情');
    			return $this->fetch('order/edit');
    		}
    	}



      public function del($id) {
    		if (empty($id)) {
    			return $this->error("非法操作！");
    		}
    		$result = model('Order')->get($id);
        if($result->delete()){
            // 删除所有的关联数据
            $result->OrderShoplist()->delete();
            return $this->success("删除成功！");
        }else{
          	return $this->error("删除失败！");
        }
    	}
}
